var uploadfile = {};
uploadfile.Common = {
    instance: function () { //获取对象
        return this;
    },

    //格式化按钮,用于grid显示
    fomatBtn: function (value, row, index, model, gd) {
        var btn = "";
        if (model === true) {
            btn += '<a  href="#" onclick="uploadfile.deleteFile( ' + row.FileId + ',\'' + gd + '\')">删除</a>';
        }
        btn += '&nbsp;<a  href="#" onclick="uploadfile.downLoad(\'' + row.FilePath + '\')" role="button">下载</a>';
        btn += '&nbsp;<a href="#" onclick="uploadfile.lookOnLine(\'' + row.FilePath + '\',' + row.FileId + ')" role="button">在线查看</a>';
        return btn;
    },
    //转换文件大小,用于grid显示
    fomatSize: function (value, row, index) {
        var filesieze = 0;
        filesieze = row.FileSize;
        filesieze = filesieze / 1024 / 1024
        filesieze = filesieze.toFixed(3);
        return filesieze;
    },
    //在线查看实现
    lookOnLine: function (FilePath, FileId) {

        var str = FilePath.split("\\");
        var fileT = str[str.length - 1].toLowerCase().split(".");
        var fileType = fileT[fileT.length - 1];

        var officeType = ["doc", "docx", "xls", "ppt", "xlsx", "pptx","txt"];
        var ySType = ["zip", "rar", "7z"];

        if (FilePath === "") { //没有上传文件

            $.messager.alert("错误提示", "没有可在线查看的文件");
            return;
        }
        if ($.inArray(fileType, officeType) > -1) {
            $.messager.progress({
                msg: "文件加载中，请稍等...",
                interval: 300
            });
            //上传的文件为office文件
            $.post("/BFSHandle.ashx?key=ConvertToImage&FileUrl=" + FilePath, function (data) {
                $.messager.progress('close');
                if (data.Result === "ERROR") {
                    $.messager.alert("提示信息", data.Message);
                    return;
                } else {
                    window.top.wdialog({
                        href: '/Common/Scripts/com/MPreviewr/Show.html',
                        title: "在线查看",
                        data: {
                            imgArr: data.Records
                        },
                        maximizable:true,
                        callback: function(thiss) {
                            if (thiss) {
                                getSetDataList(); //刷新
                            }
                        }
                    });
                }
            });

        } else if ($.inArray(fileType, ySType) > -1) {

            $.messager.alert("错误提示", "压缩文件不支持在线查看，请下载解压查看！");
            return;
        } else {
            //其他格式的文件，直接打开
            window.top.wdialog({
                href: FilePath,
                title: "在线查看",
                maximizable:true                
            });
        }
    },
    initFileList: function (element, fileIDArr, model, tbname) {
        //加载文件列表

        var fileids=[];
        if(fileIDArr!=null && fileIDArr()!=null)
        {
            $.each(fileIDArr().split(','),function(index,value){
                if(value !== null && value !== '')
                {
                    fileids.push(value);
                }
            });
        }        

        $(element).datagrid({
            singleSelect: true,
            url: "/BFSHandle.ashx?key=FileList&resultType=2",
            queryParams: {
                FileId: fileids.join(',')
            },
            columns: [[
                    { field: 'Id', title: 'Id', width: 0, hidden: true },
                    { field: 'OrgFileName', title: '文件名', width: '25%' },
                    { field: 'FileSize', title: '文件大小', width: '15%', formatter: function (value, row, index) { return uploadfile.fomatSize(value, row, index) } },
                    { field: 'FilePath', title: '文件路径', width: '30%' },
                    { field: 'operator', title: '操作', width: '30%', formatter: function (value, row, index) { return uploadfile.fomatBtn(value, row, index, model, tbname) } }
            ]]
        });

    },
    initUpload: function (options) {

        var _default={
                element:null,
                fileIDArr:null,
                model:true,
                width: 110,
                height: 35,
                swf: '/Lib/Scripts/uploadify/uploadify.swf',
                uploader: '/BFSHandle.ashx?key=FileUpload',
                auto: true,
                buttonText: "浏览",
                cancelImage: '/Lib/Scripts/uploadify/uploadify-cancel.png', //取消图片的路径
                fileSizeLimit: 0, //文件的极限大小，以字节为单位，0为不限制。1MB:1*1024*1024
                uploadLimit:0, //允许上传文件个数
                multi:true,//设置为true时可以上传多个文件。
                fileTypeDesc:'*.*',//
                fileTypeExts:'*.*',//设置可以选择的文件的类型，格式如：'*.doc;*.pdf;*.rar'。 *.*不限制  
                };
        _default = $.extend({}, _default, options);

        var element=_default.element;
        var fileIDArr=_default.fileIDArr;
        var model=_default.model;

        var tbname = "gd_" + element.id;
        var tbname1 = "up_" + element.id;
        //初始化附件列表控件
        var uploadBtn = $("<table style='width: 98%;' id='" + tbname1 + "'></table>");
        var FileList = $("<table style='width: 98%;' id='" + tbname + "'></table>");

        $(element).children().remove();
        $(element).append(uploadBtn);
        $(element).append(FileList);

        //编辑模式         
        if (model === true) {
            //生成上传文件控件
           // setTimeout(function () {
                $(uploadBtn).uploadify({
                    width: _default.width,
                    height: _default.height,
                    swf: _default.swf,
                    uploader:_default.uploader,
                    auto: _default.auto,
                    buttonText:_default.buttonText,
                    cancelImage:_default.cancelImage, //取消图片的路径
                    fileSizeLimit:_default.fileSizeLimit, //文件的极限大小，以字节为单位，0为不限制。1MB:1*1024*1024
                    uploadLimit:_default.uploadLimit, //允许上传文件个数
                    multi:_default.multi,//设置为true时可以上传多个文件。
                    fileTypeExts:_default.fileTypeExts,//设置可以选择的文件的类型，格式如：'*.doc;*.pdf;*.rar'。 *.*不限制 
                    overrideEvents : [ 'onDialogClose', 'onUploadSuccess', 'onUploadError', 'onSelectError' ],
                    //每个文件上传成功都会触发
                    onUploadSuccess: function (file, data, response) {
                        var fileId = fileIDArr(); //获取文件ID 格式以逗号分隔 1，2，3，4                         
                        var resultData = JSON.parse(data);
                        if (resultData.Result === 'OK') {
                            if (fileId === null) {
                                fileId = resultData.Id
                            } else {
                                fileId += "," + resultData.Id; //新上传成功的文件ID加入数组
                            }
                            fileIDArr(fileId); //更新值
                        } else if (resultData.result === 'ERROR') {
                            $.messager.alert("提示信息", resultData.Message);
                        }
                    },
                    //所有文件上传成功后执行
                    onQueueComplete: function (stats) {
                        uploadfile.initFileList(FileList, fileIDArr, model, tbname);
                    },                  
                    onSelectError:function(file, errorCode, errorMsg) {  
                        var msgText = "上传失败\n";  
                        switch (errorCode) {  
                            case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:  
                                msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";  
                                break;  
                            case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:  
                                msgText += "文件大小超过限制( " + this.settings.fileSizeLimit + " )";  
                                break;  
                            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:  
                                msgText += "文件大小为0";  
                                break;  
                            case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:  
                                msgText += "文件格式不正确，仅限 " + this.settings.fileTypeExts;  
                                break;  
                            default:  
                                msgText += "错误代码：" + errorCode + "\n" + errorMsg;  
                        }  
                        $.messager.alert("提示信息",msgText);
                    },
                    onUploadError:function(file, errorCode, errorMsg, errorString) {  
                        // 手工取消不弹出提示  
                        if (errorCode === SWFUpload.UPLOAD_ERROR.FILE_CANCELLED  
                                || errorCode === SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {  
                            return;  
                        }  
                        var msgText = "上传失败\n";  
                        switch (errorCode) {  
                            case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:  
                                msgText += "HTTP 错误\n" + errorMsg;  
                                break;  
                            case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:  
                                msgText += "上传文件丢失，请重新上传";  
                                break;  
                            case SWFUpload.UPLOAD_ERROR.IO_ERROR:  
                                msgText += "IO错误";  
                                break;  
                            case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:  
                                msgText += "安全性错误\n" + errorMsg;  
                                break;  
                            case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:  
                                msgText += "每次最多上传 " + this.settings.uploadLimit + "个";  
                                break;  
                            case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:  
                                msgText += errorMsg;  
                                break;  
                            case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:  
                                msgText += "找不到指定文件，请重新操作";  
                                break;  
                            case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:  
                                msgText += "参数错误";  
                                break;  
                            default:  
                                msgText += "文件:" + file.name + "\n错误码:" + errorCode + "\n"  
                                        + errorMsg + "\n" + errorString;  
                        }  
                        $.messager.alert("提示信息",msgText);  
                    }                    
                });
           // }, 10);
        }
        uploadfile.initFileList(FileList, fileIDArr, model, tbname);
    },

    deleteFile: function (fielId, gd) {
        $.post("/BFSHandle.ashx?key=FileDelete", {
            FileId: fielId
        },
        function (data) {
            if (data.Result === "ERROR") {
                $.messager.alert("提示信息", data.Message);
                return;
            } else {
                $("#" + gd).datagrid("reload");
                $.messager.alert("提示信息", "删除成功!");
            }
        });
    },

    formatDate: function (date, format) {
        if (!date) {
        	return;
        }
        if (!format) {
        	format = "yyyy-MM-dd HH:mm:ss";
        }
        switch (typeof date) {
            case "string":
                if (date.indexOf("Date") > -1) {
                    var time = date.substring(date.indexOf("(") + 1, date.lastIndexOf(")"));
                    date = new Date(parseInt(time));
                    break;
                }

                date = new Date(date.replace(/-/, "/"));
                break;
            case "number":
                date = new Date(date);
                break;
            default:
                break;
        }
        if (!date instanceof Date) {
        	return;
        }

        var paddNum = function (num) {
            num += "";
            return num.replace(/^(\d)$/, "0$1");
        }
        //指定格式字符
        var cfg = {
            yyyy: date.getFullYear() //年 : 4位
                ,
            yy: date.getFullYear().toString().substring(2) //年 : 2位
                ,
            M: date.getMonth() + 1 //月 : 如果1位的时候不补0
                ,
            MM: paddNum(date.getMonth() + 1) //月 : 如果1位的时候补0
                ,
            d: date.getDate() //日 : 如果1位的时候不补0
                ,
            dd: paddNum(date.getDate()) //日 : 如果1位的时候补0
                ,
            H: date.getHours() //时
                ,
            HH: paddNum(date.getHours()) //时
                ,
            m: date.getMinutes() //分
                ,
            mm: paddNum(date.getMinutes()) //分
                ,
            s: date.getSeconds() //秒
                ,
            ss: paddNum(date.getSeconds()) //秒
        }
        format || (format = "yyyy-MM-dd HH:mm:ss");
        return format.replace(/([a-z])(\1)*/ig, function (m) {
            return cfg[m];
        });

    },

    //下载功能
    downLoad: function (url) {

        var $iframe = $("#TempCreatedIframeElement");
        if ($iframe === null || $iframe.length === 0) {
            $iframe = $("<iframe><iframe>");
            $iframe.attr("id", "TempCreatedIframeElement");
        }
        $iframe.css("display", "none");
        $iframe.attr("src", "/BFSHandle.ashx?key=FileDownLoad&FileUrl=" + url);
        $(document.body).append($iframe);
    }
};
